package src.main.java.com.huawei.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.waf.v1.WafClient;
import com.huaweicloud.sdk.waf.v1.model.*;
import com.huaweicloud.sdk.waf.v1.region.WafRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WhiteblackipDemo {
    private static final Logger logger = LoggerFactory.getLogger(WhiteblackipDemo.class);
    public static void main(String[] args) {
        ICredential auth = new BasicCredentials()
                .withAk("<YOUR AK>")
                .withSk("<YOUR SK>");
        WafClient client = WafClient.newBuilder()
                .withCredential(auth)
                .withRegion(WafRegion.valueOf("cn-south-1"))
                .build();
        try {
            createWhiteblackip(client);
        } catch (ConnectionException e) {
            logger.error("A connect timeout exception occurs while the WAF performs some certificate-related operations, exception: {}", e);
        } catch (RequestTimeoutException e) {
            logger.error("A request timeout exception occurs while the WAF performs some certificate-related operations, exception: {}", e);
        } catch (ServiceResponseException e) {
            logger.error("there is service response error, exception: {}", e);
            logger.error("HttpStatusCode: {}", e.getHttpStatusCode());
            logger.error("RequestId: {}", e.getRequestId());
            logger.error("ErrorCode: {}", e.getErrorCode());
            logger.error("ErrorMsg: {}", e.getErrorMsg());
        }

    }

    private static CreateWhiteblackipRuleResponse createWhiteblackip(WafClient client) {
        // 初始化请求body
        CreateWhiteBlackIpRuleRequestBody createWhiteBlackIpRuleRequestBody = new CreateWhiteBlackIpRuleRequestBody()
                .withName("demo")
                .withWhite(0)
                .withDescription("demo")
                .withAddr("1.1.1.1");
        // 初始化黑白名单规则信息
        CreateWhiteblackipRuleRequest createWhiteblackipRuleRequest = new CreateWhiteblackipRuleRequest()
                .withPolicyId("PolicyId")
                .withBody(createWhiteBlackIpRuleRequestBody);
        // 创建黑白名单规则
        CreateWhiteblackipRuleResponse createWhiteblackipRuleResponse = client.createWhiteblackipRule(createWhiteblackipRuleRequest);
        logger.info(createWhiteblackipRuleResponse.toString());
        return createWhiteblackipRuleResponse;
    }
}
